<template>
  <view class="page-wrap">
    <view style="top: 0px; left: 0px; z-index: 999; width: 100%">
      <u--image :showLoading="true" mode="widthFix" :src="schema.bgurl" width="100%" height="none"></u--image>
    </view>
    <view class="form-wrap">
      <view v-if="'{}' == JSON.stringify(schema)">等待加载</view>
      <template v-else>
        <view class="f-title">{{ schema.title }}</view>
        <u--form labelPosition="left" :model="model" ref="uForm">
          <template v-for="comp in schema.components">
            <template v-if="isDesign">
              <view v-if="currentEle == comp.id" class="design-btns-wrap">
                <view class="design-btns">
                  <u-button text="复制" icon="file-text" :customStyle="btnStyle" type="success" size="mini"> </u-button>
                  <u-button text="删除" icon="trash" :customStyle="btnStyle" type="error" size="mini"> </u-button
                ></view>
              </view>
              <view v-else @click="handleTargetChange(comp.type, comp)" class="select-btn1"><u-icon name="setting" color="#666" size="24"></u-icon> </view>
            </template>
            <!-- 文本输入 -->
            <u-form-item v-if="comp.type == 'textInput'" :prop="comp.model" :labelWidth="comp.labelWidth || 45" :label="comp.label" borderBottom :ref="'c' + comp.id">
              <u--input @input="(e) => (model[comp.model] = e)" :value="model[comp.model]" border="none" :placeholder="comp.placeholder"></u--input>
            </u-form-item>

            <!-- 时间选择 -->
            <u-form-item v-else-if="comp.type == 'datetime'" @click="popups[comp.model] = true" :labelWidth="comp.labelWidth || 45" :label="comp.label" borderBottom :ref="'c' + comp.id">
              <div>{{ model[comp.model] | toDatetime }}</div>
              <u-icon slot="right" name="arrow-right"></u-icon>
              <u-datetime-picker @confirm="DTPConfirm" @cancel="DTPCancel" :show="popups[comp.model]" :modelName="comp.model" v-model="model[comp.model]" mode="datetime"></u-datetime-picker>
            </u-form-item>

            <!-- 多选框 -->
            <u-form-item v-else-if="comp.type == 'checkbox'" :labelWidth="comp.labelWidth || 45" :label="comp.label" borderBottom :ref="'c' + comp.id">
              <u-checkbox-group @change="(e) => (model[comp.model] = e)" :value="model[comp.model]" :placement="comp.placement || 'row'">
                <u-checkbox :customStyle="comp.placement && comp.placement == 'column' ? mgnBottom : mgnRight" v-for="(item, index) in comp.opts" :key="index" :label="item.name" :name="item.name">
                </u-checkbox>
              </u-checkbox-group>
            </u-form-item>

            <!-- 单选框 -->
            <u-form-item v-else-if="comp.type == 'radio'" :prop="comp.model" :labelWidth="comp.labelWidth || 45" :label="comp.label" borderBottom :ref="'c' + comp.id">
              <u-radio-group :placement="comp.placement || 'row'" :value="model[comp.model]" @change="(e) => (model[comp.model] = e)">
                <u-radio :customStyle="comp.placement && comp.placement == 'column' ? mgnBottom : mgnRight" v-for="(item, index) in comp.opts" :key="index" :label="item.name" :name="item.name">
                </u-radio>
              </u-radio-group>
            </u-form-item>

            <!-- 手机号验证 -->
            <template v-else-if="comp.type == 'phoneCheck'">
              <u-form-item :labelWidth="comp.labelWidth || 45" :label="comp.label" borderBottom :ref="'c' + comp.id">
                <u--input @input="(e) => (model[comp.model] = e)" :value="model[comp.model]" border="none" :placeholder="comp.placeholder"></u--input>
              </u-form-item>

              <u-form-item :labelWidth="comp.labelWidth || 45" label="验证码" borderBottom :ref="'cx' + comp.id">
                <u--input @input="(e) => (sms.code = e)" :value="sms.code" border="none" placeholder="手机验证码" />
                <u-button :disabled="sms.dotTime == 0 ? false : true" @click="sendSMS(comp.model)" :customStyle="sms.btnStyle" :text="smsBtnText" type="success" size="small" />
              </u-form-item>
            </template>

            <view class="u-demo-block" v-else-if="comp.type == 'upload'">
              <text class="u-demo-block__title" style="color: #303133; font-size: 15px; line-height: 30px">{{ comp.label }}</text>
              <view class="u-demo-block__content">
                <view class="u-page__upload-item">
                  <u-upload :fileList="model[comp.model]" name="3" multiple :maxCount="2" :previewFullImage="true"></u-upload>
                </view>
              </view>
            </view>
          </template>
        </u--form>
      </template>
    </view>
    <view style="height: 200upx"></view>
  </view>
</template>

<script>
import { getRule, getDefault } from './service'
function __Constructor__(sc) {
  return sc['components'].reduce(
    (pre, cur) => {
      if (cur.model) pre.model[cur.model] = getDefault(cur)
      if (cur.ruletype) pre.rules[cur.model] = getRule(cur)
      if (cur.withpop) pre.popups[cur.model] = false
      return pre
    },
    { model: {}, popups: {}, rules: {} }
  )
}

var interJob = null
export default {
  name: 'FormRender',
  data() {
    return {
      mgnBottom: { marginBottom: '14px' },
      mgnRight: { marginRight: '8px' },
      sms: {
        reTryCycle: 30,
        dotTime: 0,
        code: '',
        btnStyle: {
          width: '86px',
          position: 'absolute',
          'margin-top': '-4px',
          right: '12px',
          'z-index': '999',
        },
      },
      smsCheck: {
        code: '',
        expiration: 0,
      },
      btnStyle: {
        width: '56px',
        'margin-right': '6px',
      },
      currentEle: '001',
      schema: {},
      model: {},
      popups: {},
      isDesign: false,
    }
  },
  computed: {
    smsBtnText() {
      return this.sms.dotTime == 0 ? '发送验证码' : this.sms.dotTime + 'S'
    },
  },
  watch: {},
  created() {
    console.log('# on FormRender created')
    const value = uni.getStorageSync('smsCheck')
    if (value) this.smsCheck = value
  },
  mounted() {},
  methods: {
    handleTargetChange(type, data) {
      this.currentEle = data['id']
      this.$emit('handleTargetChange', type, data)
    },
    showPopup(p) {
      this.popups[p] = true
    },
    load({ schema, initData = false, isDesign = false }) {
      if (isDesign) this.isDesign = true
      const { model, popups, rules } = __Constructor__(schema)
      this.popups = popups
      this.model = initData ? initData : model
      this.schema = schema
      if (schema['smscheck'] && schema['smscycle']) {
        this.sms['reTryCycle'] = schema['smscycle']
      }
      setTimeout(() => {
        this.$refs.uForm.setRules(rules)
        if (this.schema.components.length > 0) {
          const t = this.schema.components[0]
          this.handleTargetChange(t['type'], t)
        }
      })
    },
    getSchema() {
      return this.schema
    },
    async getData() {
      try {
        const res = await this.$refs.uForm.validate()
        return this.model
      } catch (e) {
        console.log('校验失败:', e)
        return false
      }
    },
    checkSms() {
      if (!this.schema['smscheck']) return true
      if (!this.sms.code) {
        this.$toast('请输入验证码！')
        return false
      }

      const { code, expiration } = this.smsCheck
      if (!code) {
        this.$toast('请点击发送验证码！')
        return false
      }

      const now = this.$dayjs().unix()
      if (now >= expiration) {
        this.$toast('验证码已过期！')
        return false
      }

      if (this.sms.code != code) {
        this.$toast('验证码不正确！')
        return false
      }

      return true
    },

    DTPConfirm(e) {
      console.log('DTPConfirm', e)
      this.popups[e.modelName] = false
    },
    DTPCancel(target) {
      console.log('DTPCancel', target)
      this.popups[target] = false
    },
    DTPChange(e) {
      console.log('DTPChange', e)
    },
    DTPClose(target) {
      console.log('DTPClose', target)
      this.popups[target] = false
    },
    groupChange(e) {
      console.log('groupChange', e)
    },
    clickAll(e) {
      console.log(e)
    },
    codeChange(e) {
      console.log('codeChange', e)
    },

    // 发送验证码
    async sendSMS(k) {
      const phone = this.model[k]
      if (!phone.match(/^[1]{1}[0-9]{10}$/)) return alert('请输入11位手机号码')
      const code = (((Math.random() * 0.8 + 0.1) * 10 ** 4) | 0).toString()
      const expiration = this.$dayjs().add(5, 'minute').unix()
      const res = await uni.$u.http.post(`/weixinNotify/SmsExp?methodName=sendSMS&phoneNum=${phone}&tempid=SMS_464510938&vcode=${code}`)
      if (res != '保存成功') return
      setTimeout(this.updateSendSmsBtnText, 1000)
      this.sms.dotTime = this.sms.reTryCycle
      this.smsCheck = { code, expiration }
      uni.setStorageSync('smsCheck', this.smsCheck)
    },

    updateSendSmsBtnText() {
      this.sms.dotTime--
      if (this.sms.dotTime > 0) setTimeout(this.updateSendSmsBtnText, 1000)
    },
  },
}
</script>

<style lang="scss" scoped>
.page-wrap {
}
.form-wrap {
  padding: 0 12px;
}
.f-title {
  padding: 12px 0;
  text-align: center;
  font-size: 20px;
}
.design-btns-wrap {
  width: calc(98vw);
  position: absolute;
  margin-left: -10px;
  height: 40px;
  border: 2px solid #398ade;
  z-index: 9999;
  border-radius: 4px;
}
.design-btns {
  display: flex;
  align-items: center;
  position: absolute;
  bottom: 4px;
  right: 0px;
}

.select-btn1 {
  margin-top: 6px;
  position: absolute;
  background: #eee;
  padding: 3px;
  border-radius: 3px;
  right: 12px;
  z-index: 999;
}
</style>
